package com.mk.wardsystemserver.controller;

import com.mk.wardsystemserver.pojo.Admin;
import com.mk.wardsystemserver.pojo.AdminLoginParam;
import com.mk.wardsystemserver.pojo.RespBean;
import com.mk.wardsystemserver.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Api(tags = "LoginController")
@RestController
public class LoginController {
    @Autowired
    private IAdminService adminService;
    @ApiOperation(value = "登陆之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return  adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),request);
    }

    @ApiOperation(value="获取当前用户登录信息")
    @GetMapping("/admin/info")
    //通过Principal这个对象获取当前登录对象
    public Admin getAdminInfo(Principal principal){
        if(null==principal){
            return  null;
        }
        String username=principal.getName();
        Admin admin=adminService.getAdminByUserName(username);
        //用户密码不返回给前端，前端的密码没有什么用，有用户密码被泄露的风险等等
        admin.setPassword(null);
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }

    @ApiOperation(value="退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("退出登录成功");
    }
}
